import { asyncRoutes, constantRoutes } from "../../router/index";

const state = () => ({
  routes: [],
  addRoutes: []
});

const mutations = {
  SET_ROUTES(state, routes) {
    state.addRoutes = routes;
    state.routes = constantRoutes.concat(routes);
  }
};
const getters = {
  getRoutes(state) {
    return state.routes;
  }
};
function hasPermission(rolse: any, tmp: any) {
  if (tmp && tmp.authentication) {
    return rolse.some(role => {
      return role.authentication === tmp.authentication;
    });
  } else {
    return true;
  }
}

function RolesChildren(val: any, name: string) {
  let result = "";
  for (let i = 0; i < val.length; i++) {
    if (val[i].name === name) {
      result = val[i].children;
      break;
    }
  }
  return result;
}

function filterAsyncRoutes(routes: any, rolse: any) {
  const res: any[] = [];
  routes.forEach((route, index) => {
    const tmp = { ...route };
    if (hasPermission(rolse, tmp)) {
      if (tmp.children) {
        const childAll = RolesChildren(rolse, tmp.name);
        tmp.children = filterAsyncRoutes(tmp.children, childAll);
      }
      res.push(tmp);
    }
  });
  return res;
}
const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise((resolve, reject) => {
      let accessedRoutes;
      accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
      commit("SET_ROUTES", accessedRoutes);
      resolve(accessedRoutes);
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
};
